from fastapi import FastAPI, HTTPException, APIRouter
from pydantic import BaseModel, Field, ValidationError
from datetime import datetime
from typing import List, Optional
import uvicorn


app03=APIRouter()

class Student(BaseModel):
    stu_id: str = Field(..., description="学生唯一ID，字符串格式")
    open: str = Field(..., pattern=r"^\d{4}-\d{2}-\d{2}$", description="开通日期，格式：YYYY-MM-DD")
    offer: str = Field(..., pattern=r"^\d{4}-\d{2}-\d{2}$", description="offer日期，格式：YYYY-MM-DD")
    company: str = Field(..., max_length=15, min_length=3, description="公司名称，3-15字")
    salary: float = Field(..., description="薪资")

    # # 可以添加配置，方便从字典加载时处理日期字符串
    # class Config:
    #     json_encoders = {
    #         datetime: lambda v: v.strftime("%Y-%m-%d")
    #     }

students=[
    {"stu_id":"1001","open":"2024-01-01","offer":"2024-03-12","company":"深圳中软","salary":20000},
    {"stu_id":"1002","open":"2024-03-01","offer":"2024-06-12","company":"字节跳动","salary":30000},
    {"stu_id":"1003","open":"2024-02-15","offer":"2024-04-20","company":"腾讯科技","salary":28000},
    {"stu_id":"1004","open":"2024-01-20","offer":"2024-03-30","company":"阿里巴巴","salary":26000},
    {"stu_id":"1005","open":"2024-04-05","offer":"2024-07-08","company":"华为技术","salary":32000},
    {"stu_id":"1006","open":"2024-02-28","offer":"2024-05-15","company":"百度在线","salary":25000},
    {"stu_id":"1007","open":"2024-03-15","offer":"2024-06-25","company":"京东集团","salary":24000},
    {"stu_id":"1008","open":"2024-01-10","offer":"2024-03-18","company":"美团点评","salary":23000},
    {"stu_id":"1009","open":"2024-04-20","offer":"2024-07-22","company":"小米科技","salary":27000},
    {"stu_id":"1010","open":"2024-02-05","offer":"2024-04-12","company":"网易公司","salary":22000},
    {"stu_id":"1011","open":"2024-03-25","offer":"2024-06-30","company":"拼多多","salary":31000},
    {"stu_id":"1012","open":"2024-01-25","offer":"2024-04-05","company":"快手科技","salary":26000},
    {"stu_id":"1013","open":"2024-04-10","offer":"2024-07-15","company":"滴滴出行","salary":25000},
    {"stu_id":"1014","open":"2024-02-18","offer":"2024-05-02","company":"携程旅行","salary":21000},
    {"stu_id":"1015","open":"2024-03-10","offer":"2024-06-18","company":"小红书","salary":24000},
    {"stu_id":"1016","open":"2024-01-05","offer":"2024-03-22","company":"顺丰科技","salary":23000},
    {"stu_id":"1017","open":"2024-04-25","offer":"2024-07-28","company":"字节跳动（上海）","salary":30000}
]

# 1. 分页查询（修复路由命名，规范响应）
@app03.get('/read/{skip}/{limit}', response_model=List[Student], description="分页查询学生信息，每页5条")
async def read_students(skip: int, limit: int):
    """
    - skip: 页码（从1开始）
    - limit: 每页条数（建议≤20）
    返回：对应页的学生数据列表
    """
    start = (skip - 1) * 5
    end = start + limit
    return students[start:end] if 0 <= start < len(students) else []

# 2. 按ID查询（修复路由拼写，明确异常处理）
@app03.get('/stu_id/{stu_id}', response_model=Optional[Student], description="通过ID精确查询")
async def read_id_stu(stu_id: str):
    """根据stu_id查询，找不到返回 None（FastAPI 自动转404需结合 HTTPException）"""
    for stu in students:
        if stu["stu_id"] == stu_id:
            return stu
    raise HTTPException(status_code=404, detail=f"学生ID {stu_id} 未找到")

# 3. 添加学生（修复重复ID校验，规范响应模型）
@app03.post('/add_stu', response_model=Student, description="新增学生信息，ID重复则报错")
async def add_student(student: Student):
    # 校验ID是否已存在
    for stu in students:
        if stu["stu_id"] == student.stu_id:
            raise HTTPException(status_code=400, detail=f"ID {student.stu_id} 已存在，无法重复添加")
    # 转换为字典后添加（保持列表元素类型统一）
    students.append(student.dict())
    return student  # 直接返回模型实例，符合 response_model

# 4. 修改学生（修复未找到场景，严格模型替换）
@app03.put('/mod_student/{stu_id}', response_model=Optional[Student], description="根据ID修改信息")
async def mod_student(stu_id: str, new_student: Student):
    for index, stu in enumerate(students):
        if stu['stu_id'] == stu_id:
            # 替换为新数据（字典格式）
            students[index] = new_student.dict()
            return new_student  # 返回更新后的模型
    raise HTTPException(status_code=404, detail=f"学生ID {stu_id} 未找到，无法修改")



# 5. 删除学生（修复类型不一致、删除逻辑错误）
@app03.delete('/del_stu/{stu_id}', response_model=dict, description="根据ID删除学生信息")
async def del_stu(stu_id: str):  # 与 Student.stu_id 类型统一为 str
    for index, stu in enumerate(students):
        if stu["stu_id"] == stu_id:
            del students[index]  # 通过索引删除，解决原逻辑错误
            return {"message": "删除成功", "deleted_stu_id": stu_id}
    raise HTTPException(status_code=404, detail=f"学生ID {stu_id} 未找到，无法删除")


